package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.controller.mq.listener.vo.IotMsgNotifyData;
import com.zzyl.nursing.controller.mq.listener.vo.IotMsgService;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备数据Service业务层处理
 *
 * @author alexis
 * @date 2025-10-14
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 批量插入设备数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    @Transactional
    public void insertBatchDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //通过设备id查设备
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, iotMsgNotifyData.getHeader().getDeviceId()).one();
        //判断设备是否存在
        if (device == null) {
            return;
        }
        List<DeviceData> list = new ArrayList<>();
        iotMsgNotifyData.getBody().getServices().forEach(service -> {

            Map<String, Object> properties = service.getProperties();
            if (CollUtil.isEmpty(properties)) {
                return;
            }
            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            properties.forEach((key, value) -> {
                //构建设备数据
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                //使主键自增
                deviceData.setId(null);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setFunctionId(key);
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(alarmTime);
                //变量添加到集合
                list.add(deviceData);
            });
        });
        //批量插入设备数据
        saveBatch(list);
        //缓存设备最新数据
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId(), JSONUtil.toJsonStr( list));
    }

    /**
     * 定时删除设备数据（保留15天内的数据）
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDeviceData() {
        final int DAYS_TO_KEEP = 15;
        LocalDateTime fifteenDaysAgo = LocalDateTime.now().minusDays(DAYS_TO_KEEP);
        log.info("开始执行设备数据清理任务，删除 {} 天前的数据，截止时间: {}", DAYS_TO_KEEP, fifteenDaysAgo);

        //构建删除条件
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(DeviceData::getAlarmTime, fifteenDaysAgo);

        //执行删除并获取删除数量
        int deletedCount = baseMapper.delete(queryWrapper);

        log.info("设备数据清理任务完成，共删除 {} 条记录", deletedCount);
    }
}
